﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.Contract;
using MaxLeaf.Platform.DALImplementation;
using MaxLeaf.Platform.DataContract;
using CommonsLib.Utility;
using CommonsLib.Settings;
using System.Data;
using MaxLeaf.Platform.Functions;
using MaxLeaf.Platform.BRL;
using MaxLeaf.Platform.Commons;

using CommonsLib.DB;

namespace MaxLeaf.Platform.BLLImplementation
{
    public class mCompanyBLL :BaseBLL 
    {
        public mCompanyBLL()
        {
            
        }
        
        public override string FinterIDFields
        {
            get
            {
                return string.Format("{0},{1}", "CompanyId", (int)FinterIDType.Company);
            }
        }

        public override object Add(object model)
        {
            mCompanyDataModel company = (mCompanyDataModel)model;
            company.PassWord = MD5Func.Hash(company.PassWord);
            return base.Add(company);
        }


        protected override void Delete_AfterTrans(DBAccess dbcon, object model)
        {
            try
            {
                ((mCompanyDAL)this.CurrentDAL).Delete_Web(dbcon, model);
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }
        }
        protected override void Add_After(DBAccess dbcon, object model)
        {
            return ;
        }

        protected override void Update_AfterTrans(DBAccess dbcon, object model)
        {
            try{
            Update_Web(dbcon, model);
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }
        }

        public void Update_Web(DBAccess dbcon, object model)
        {
            bool blnIsDirect = false; //2,25, 27,32
            mCompanyDataModel mOCompany = model as mCompanyDataModel;
            if (mOCompany != null)
            {
                string strSQL = "Delete From mLog where KeyValue='" + mOCompany.Key + "' and LogType='mCompany'";
                dbcon.ExecuteSql(strSQL);

                strSQL = @"insert into mLog(LogType,KeyValue,OldKeyValue,LogStatus) 
                                  values ('{0}','{1}','{2}','{3}')";
                strSQL = string.Format(strSQL, "mCompany"
                                               , mOCompany.Key
                                               , ""
                                               , "0"
                                       );
                dbcon.ExecuteSql(strSQL);

                strSQL = "select * from mLog where LogType='mCompany'";
                DataTable dtLog = dbcon.GetDataTable(strSQL);
                foreach (DataRow drLog in dtLog.Rows)
                {
                    try
                    {
                        mCompany_InfoDataModel mCompanyInfo = (mCompany_InfoDataModel)BaseBLL.GetDataModelBLL("mCompany_InfoDataModel").Select(new mCompany_InfoDataModel(), CvtFunc.ToInt(drLog["KeyValue"]));
                        
                        if (mCompanyInfo.ProvID == 2 || mCompanyInfo.ProvID == 25 || mCompanyInfo.ProvID == 27 || mCompanyInfo.ProvID == 32)
                        {
                            blnIsDirect = true;
                        }
                        else
                        {
                            blnIsDirect = false;
                        }
                        string strUserSN = GetUserSN(blnIsDirect, mCompanyInfo.ProvID, mCompanyInfo.CityID, mCompanyInfo.RegionID);
                        
                        if (((mCompanyDAL)this.CurrentDAL).Update_Web(dbcon, model, strUserSN))
                        {
                            strSQL = "Delete From mLog where LogType='mCompany' and KeyValue='" + CvtFunc.ToInt(drLog["KeyValue"]) + "'";
                            dbcon.ExecuteSql(strSQL);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Debug(ex.Message);
                    }
                }
            }
        }         
      
        public static int GetParentCompanyID(int intCompanyID)
        {
            using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
            {
                return mCompanyDAL.GetParentCompanyID(dbcon, intCompanyID);
            }
        }

        internal bool InitData(int intFromCompanyID, int intToCompanyID)
        {
            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    try
                    {
                        //dbcon.BeginTrans();

                        ((mCompanyDAL)this.CurrentDAL).InitData(dbcon, intFromCompanyID, intToCompanyID);



                        //dbcon.CommitTrans();

                    }
                    catch (Exception ex)
                    {
                        LogManager.Debug(ex.Message);
                        //dbcon.RollbackTrans();
                        throw;
                    }

                    
                }
                ts.Complete();
                return true;
            }
        }

        internal string GetUserSN(bool blnDirectCity, int intProvID, int intCityID, int intRegionID)
        {
            try
            {
                string strUserSN = string.Empty;
                string strUserSNSt = GetUserSNSt(blnDirectCity, intProvID, intCityID, intRegionID);
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_WebRead)))
                {
                    strUserSN = ((mCompanyDAL)this.CurrentDAL).GetUserSN(dbcon, strUserSNSt);
                }
                if (string.IsNullOrEmpty(strUserSN))
                {
                    return string.Format("{0}{1}", strUserSNSt, "000001");
                }
                else
                {
                    return string.Format("{0}{1:000000}", strUserSNSt, CvtFunc.ToInt(CvtFunc.ToRightString(strUserSN, 6)) + 1);
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug(ex.Message);
                throw new MaxLeafException(ex.ToString()); 
            }
        }

        private string  GetUserSNSt(bool blnDirectCity, int intProvID, int intCityID, int intRegionID)
        {
            if (blnDirectCity)
            {
                return string.Format("{0:00}{1:0000}", intProvID, intRegionID);
            }
            else
            {
                return string.Format("{0:00}{1:0000}", intProvID, intCityID);
            }
        }

        internal double GetMonthAppliedAmt(int intCompanyID)
        {
            using (DBAccess dbcon = DataFunc.GetDBAccessByDataModelType(typeof(mCompanyDataModel)))
            {
                return CvtFunc.ToDouble(DataFunc.GetFieldValue(dbcon, "mCompany_Info", "MonthAppliedAmt", new Dictionary<string, object> { { "CompanyID", intCompanyID } }));
            }
        }

        
    }
}
